<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\Exception;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\Request;

class Course
{
    /**
     * 课程列表
     */
   public function list(){
       return '课程列表';
   }

    /**
     * 课程添加
     */
   public function add(){

       try {

           # 接收参数
           $param = \request()->all();
           $param['name'] = trim($param['name']);
           validate(\app\api\validate\Course::class)->check($param);


           # 添加入库
           # 文件上传
           $path = Filesystem::disk('public')->putFile('image',$param['logo']);
           # 生成缩略图 文字水印 安装图像处理扩展
           $image = \think\Image::open('./storage/'.$path);
            // 按照原图的比例生成一个最大为80*80的缩略图并保存为thumb.png
//           $image->thumb(80, 80)->text("2004a",getcwd().'/font.ttf',14,"#FF0000")->save('./storage/'.$path);

           $param['logo'] = $path;
            \app\api\model\Course::create($param);
            return  success();

       }catch (ValidateException $validateException) {
           return  fail([],$validateException->getError(),$validateException->getCode());
       }catch (HttpException $httpException) {
           return  fail([],$httpException->getMessage(),$httpException->getCode());
       }catch (Exception $exception) {
           return  fail([],$exception->getMessage(),$exception->getCode());
       }

       return "课程添加";

   }

    /**
     * 删除接口
     */
   public function del(){
        $id = \request()->get('id');
        if (!is_numeric($id)) {
            return fail();
        }

        $info = \app\api\model\Course::find($id);
        if ($info->on_sale == 1) {
            return fail([],'课程已上架、不能删除');
        }

        \app\api\model\Course::destroy($id);
        return  success();
   }

   /**
    * 批量删除的接口
    */

   public function batchDel(){
       $ids = \request()->get('ids');
       if (empty($ids)) {
           return fail([],'参数错误');
       }

       $is_onsale = \app\api\model\Course::whereIn('id',$ids)->where('on_sale',1)->select()->toArray();

       if (!empty($is_onsale)) {
           return fail([],'数据里面有已上架、不能删除');
       }
       $ids = explode(',',$ids);



       \app\api\model\Course::destroy($ids);
       return  success();

   }
}

